/*
 * SPDX-FileCopyrightText: 2021-2022 Espressif Systems (Shanghai) CO LTD
 *
 * SPDX-License-Identifier: Unlicense OR CC0-1.0
 */

/****************************************************************************
 *
 * This demo showcases BLE GATT server. It can send adv data, be connected by client.
 * Run the gatt_client demo, the client demo will automatically connect to the gatt_server demo.
 * Client demo will enable gatt_server's notify after connection. The two devices will then exchange
 * data.
 *
 ****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <inttypes.h>
#include "freertos/FreeRTOS.h"
#include "freertos/task.h"
#include "freertos/event_groups.h"
#include "esp_system.h"
#include "esp_log.h"
#include "nvs_flash.h"
#include "esp_bt.h"

#include "esp_gap_ble_api.h"
#include "esp_gatts_api.h"
#include "esp_bt_defs.h"
#include "esp_bt_main.h"
#include "esp_gatt_common_api.h"

#include "sdkconfig.h"



const char *TAG = "main";

// Declare the static function
static void gatts_profile_a_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param);

#define GATTS_SERVICE_UUID_A 0x1000
#define GATTS_CHAR_UUID_A 0x1100
#define GATTS_DESCR_UUID_A 0x1110
#define GATTS_HANDLE_NUM_A 4

#define DEVICE_NAME "BLE module A"
#define MANUFACTURER_DATA {0x7D, 0x02, 'R', 'o', 'l', 'a', 'n', 'd'};
#define MANUFACTURER_DATA_LEN 8

#define GATTS_DEMO_CHAR_VAL_LEN_MAX 0x40

#define PREPARE_BUF_MAX_SIZE 1024

#define CHAR1_STR "demo_char1_str"
#define CHAR1_DESC_STR "This is a demo description"
// static uint8_t char1_str[] = {0x11, 0x22, 0x33};

static esp_gatt_char_prop_t property_a = 0; // 存放服务A的特征的属性
static esp_gatt_perm_t permission_a = 0;    // 存放服务A的特征的权限
static uint8_t esp_gatt_manu_data[] = MANUFACTURER_DATA;
static esp_attr_value_t gatts_char1_val =
    {
        .attr_max_len = GATTS_DEMO_CHAR_VAL_LEN_MAX,
        .attr_len = strlen(CHAR1_STR),
        .attr_value = (uint8_t *)CHAR1_STR,
};
static esp_attr_value_t gatts_char1_desc_val =
    {
        .attr_max_len = GATTS_DEMO_CHAR_VAL_LEN_MAX * 2,
        .attr_len = strlen(CHAR1_DESC_STR),
        .attr_value = (uint8_t *)CHAR1_DESC_STR,
};

#define adv_config_flag (1 << 0)
#define scan_rsp_config_flag (1 << 1)
// 当此变量的第二位都被置零后，表示广播信息配置完毕
static uint8_t adv_config_done = adv_config_flag | scan_rsp_config_flag;

static uint8_t adv_service_uuid128[16 * 1] = {
    /* LSB <--------------------------------------------------------------------------------> MSB */
    // first server uuid, 16bit, [12],[13] is the value
    0xfb,
    0x34,
    0x9b,
    0x5f,
    0x80,
    0x00,
    0x00,
    0x80,
    0x00,
    0x10,
    0x00,
    0x00,
    0xFF,
    0x00,
    0x00,
    0x00};

// The length of adv data must be less than 31 bytes
// adv data
static esp_ble_adv_data_t adv_data = {
    .set_scan_rsp = false,
    .include_name = true,
    .include_txpower = false,
    .min_interval = 0x0006, // slave connection min interval, Time = min_interval * 1.25 msec
    .max_interval = 0x0010, // slave connection max interval, Time = max_interval * 1.25 msec
    .appearance = 0x00,
    .manufacturer_len = 0,       // MANUFACTURER_DATA_LEN,
    .p_manufacturer_data = NULL, // (uint8_t *)MANUFACTURER_DATA,
    .service_data_len = 0,
    .p_service_data = NULL,
    // .service_uuid_len = sizeof(adv_service_uuid128),
    // .p_service_uuid = adv_service_uuid128,
    .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};

// scan response data
static esp_ble_adv_data_t scan_rsp_data = {
    .set_scan_rsp = true,
    .include_name = true,
    //.include_txpower = true,
    //.min_interval = 0x0006,
    //.max_interval = 0x0010,
    .appearance = 0x00,
    .manufacturer_len = MANUFACTURER_DATA_LEN,
    .p_manufacturer_data = esp_gatt_manu_data,
    .service_data_len = 0,
    .p_service_data = NULL,
    // .service_uuid_len = sizeof(adv_service_uuid128), // 被扫描时隐藏服务
    // .p_service_uuid = adv_service_uuid128,
    .flag = (ESP_BLE_ADV_FLAG_GEN_DISC | ESP_BLE_ADV_FLAG_BREDR_NOT_SPT),
};

static esp_ble_adv_params_t adv_params = {
    .adv_int_min = 0x20,
    .adv_int_max = 0x40,
    .adv_type = ADV_TYPE_IND,
    .own_addr_type = BLE_ADDR_TYPE_PUBLIC,
    //.peer_addr            =
    //.peer_addr_type       =
    .channel_map = ADV_CHNL_ALL,
    .adv_filter_policy = ADV_FILTER_ALLOW_SCAN_ANY_CON_ANY,
};

#define PROFILE_NUM 1
#define PROFILE_A_APP_ID 0

struct gatts_profile_inst
{
  esp_gatts_cb_t gatts_cb; // 回调函数
  uint16_t gatts_if;
  uint16_t app_id;
  uint16_t conn_id;
  uint16_t service_handle;       // 服务属性句柄
  esp_gatt_srvc_id_t service_id; // 服务 ID
  uint16_t char_handle;          // 特性句柄
  esp_bt_uuid_t char_uuid;       // 特性 UUID
  esp_gatt_perm_t perm;
  esp_gatt_char_prop_t property;
  uint16_t descr_handle;
  esp_bt_uuid_t descr_uuid;
};

/* One gatt-based profile one app_id and one gatts_if, this array will store the gatts_if returned by ESP_GATTS_REG_EVT */
static struct gatts_profile_inst gl_profile_tab[PROFILE_NUM] = {
    [PROFILE_A_APP_ID] = {
        .gatts_cb = gatts_profile_a_event_handler,
        .gatts_if = ESP_GATT_IF_NONE, /* Not get the gatt_if, so initial is ESP_GATT_IF_NONE */
    }};

typedef struct
{
  uint8_t *prepare_buf;
  int prepare_len;
} prepare_type_env_t;

static prepare_type_env_t a_prepare_write_env;

void example_write_event_env(esp_gatt_if_t gatts_if, prepare_type_env_t *prepare_write_env, esp_ble_gatts_cb_param_t *param);

/**
 * @brief BLE GAP 事件处理程序
 * @param event 事件类型
 * @param param 事件参数
 */
static void gap_event_handler(esp_gap_ble_cb_event_t event, esp_ble_gap_cb_param_t *param)
{
  switch (event)
  {
  case ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: // 原始广播数据设置完成事件
    ESP_LOGI(TAG, "ESP_GAP_BLE_ADV_DATA_SET_COMPLETE_EVT: ");
    adv_config_done &= (~adv_config_flag);
    if (adv_config_done == 0) // 如果所有广播数据都设置完成，启动广播
      esp_ble_gap_start_advertising(&adv_params);
    break;

  case ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: // 扫描响应数据设置完成事件
    ESP_LOGI(TAG, "ESP_GAP_BLE_SCAN_RSP_DATA_SET_COMPLETE_EVT: ");
    adv_config_done &= (~scan_rsp_config_flag);
    if (adv_config_done == 0) // 如果所有扫描响应数据都设置完成，启动广播
      esp_ble_gap_start_advertising(&adv_params);
    break;

  case ESP_GAP_BLE_ADV_START_COMPLETE_EVT: // 广播启动完成事件，用于指示广播是否成功启动
    ESP_LOGI(TAG, "ESP_GAP_BLE_ADV_START_COMPLETE_EVT: ");
    if (param->adv_start_cmpl.status != ESP_BT_STATUS_SUCCESS)
      ESP_LOGE(TAG, "广播启动失败");
    break;

  case ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: // 广播停止完成事件
    ESP_LOGI(TAG, "ESP_GAP_BLE_ADV_STOP_COMPLETE_EVT: ");
    if (param->adv_stop_cmpl.status != ESP_BT_STATUS_SUCCESS)
      ESP_LOGE(TAG, "广播停止失败");
    break;

  case ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: // 更新连接参数事件
    ESP_LOGI(TAG, "ESP_GAP_BLE_UPDATE_CONN_PARAMS_EVT: ");
    ESP_LOGI(TAG, "更新连接参数状态 = %d, 最小间隔 = %d, 最大间隔 = %d, 连接间隔 = %d, 延迟 = %d, 超时 = %d",
             param->update_conn_params.status,
             param->update_conn_params.min_int,
             param->update_conn_params.max_int,
             param->update_conn_params.conn_int,
             param->update_conn_params.latency,
             param->update_conn_params.timeout);
    break;
  default:
    ESP_LOGI(TAG, "ESP_GAP_BLE_XXX_EVT: [%d]", event);
    break;
  }
}

/**
 * @brief 处理 GATT 服务器的写事件
 *
 * @param gatts_if GATT 服务器接口
 * @param prepare_write_env 预写环境
 * @param param GATT 事件参数
 */
void example_write_event_env(esp_gatt_if_t gatts_if, prepare_type_env_t *prepare_write_env, esp_ble_gatts_cb_param_t *param)
{
  esp_gatt_status_t status = ESP_GATT_OK;
  if (param->write.need_rsp)
  {
    ESP_LOGI(TAG, "This write event need response");
    if (param->write.is_prep)
    {
      ESP_LOGI(TAG, "This write event is prepare writing");
      if (prepare_write_env->prepare_buf == NULL)
      {
        // 如果预写缓冲区为空，分配内存并初始化
        prepare_write_env->prepare_buf = (uint8_t *)malloc(PREPARE_BUF_MAX_SIZE * sizeof(uint8_t));
        prepare_write_env->prepare_len = 0;
        if (prepare_write_env->prepare_buf == NULL)
        {
          ESP_LOGE(TAG, "Gatt_server prep no mem");
          status = ESP_GATT_NO_RESOURCES;
        }
      }

      // 检查偏移量和长度是否有效
      if (param->write.offset > PREPARE_BUF_MAX_SIZE)
        status = ESP_GATT_INVALID_OFFSET;
      else if ((param->write.offset + param->write.len) > PREPARE_BUF_MAX_SIZE)
        status = ESP_GATT_INVALID_ATTR_LEN;

      // 创建 GATT 响应并填充数据
      esp_gatt_rsp_t *gatt_rsp = (esp_gatt_rsp_t *)malloc(sizeof(esp_gatt_rsp_t));
      gatt_rsp->attr_value.len = param->write.len;
      gatt_rsp->attr_value.handle = param->write.handle;
      gatt_rsp->attr_value.offset = param->write.offset;
      gatt_rsp->attr_value.auth_req = ESP_GATT_AUTH_REQ_NONE;
      memcpy(gatt_rsp->attr_value.value, param->write.value, param->write.len);

      // 发送 GATT 响应
      esp_err_t response_err = esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, status, gatt_rsp);
      if (response_err != ESP_OK)
        ESP_LOGE(TAG, "发送响应错误");
      else
      {
        ESP_LOGI(TAG, "Responsed :");
        esp_log_buffer_hex(TAG, gatt_rsp->attr_value.value, gatt_rsp->attr_value.len);
      }
      free(gatt_rsp);
      if (status != ESP_GATT_OK)
      {
        return;
      }

      // 将写入的数据复制到预写缓冲区
      memcpy(prepare_write_env->prepare_buf + param->write.offset,
             param->write.value,
             param->write.len);
      prepare_write_env->prepare_len += param->write.len;
    }
    else
    {
      // 如果不是预写，直接发送响应
      esp_ble_gatts_send_response(gatts_if, param->write.conn_id, param->write.trans_id, status, NULL);
    }
  }
}


static void gatts_event_handler(esp_gatts_cb_event_t event, esp_gatt_if_t gatts_if, esp_ble_gatts_cb_param_t *param)
{
  switch (event)
  {
  case ESP_GATTS_REG_EVT: // GATTS 应用注册事件
  {
    ESP_LOGI(TAG, "ESP_GATTS_REG_EVT, status %d, app_id %d", param->reg.status, param->reg.app_id);
    if (param->reg.status == ESP_GATT_OK)
    {
      gl_profile_tab[param->reg.app_id].gatts_if = gatts_if;
    }
    else
    {
      ESP_LOGE(TAG, "Reg app failed, app_id %04x, status %d",
               param->reg.app_id,
               param->reg.status);
      return;
    }
    // 写入 GATTS 配置文件
    gl_profile_tab[PROFILE_A_APP_ID].service_id.is_primary = true;
    gl_profile_tab[PROFILE_A_APP_ID].service_id.id.inst_id = 0x00;
    gl_profile_tab[PROFILE_A_APP_ID].service_id.id.uuid.len = ESP_UUID_LEN_16;
    gl_profile_tab[PROFILE_A_APP_ID].service_id.id.uuid.uuid.uuid16 = GATTS_SERVICE_UUID_A;
    // 创建服务
    esp_ble_gatts_create_service(gatts_if, &gl_profile_tab[PROFILE_A_APP_ID].service_id, GATTS_HANDLE_NUM_A);
    break;
  }
  case ESP_GATTS_READ_EVT:
  {
    ESP_LOGI(TAG, "GATT_READ_EVT, conn_id %d, trans_id %" PRIu32 ", handle %d", param->read.conn_id, param->read.trans_id, param->read.handle);
    esp_gatt_rsp_t rsp;
    memset(&rsp, 0, sizeof(esp_gatt_rsp_t));
    rsp.attr_value.handle = param->read.handle;
    rsp.attr_value.len = 4;
    rsp.attr_value.value[0] = 0xde;
    rsp.attr_value.value[1] = 0xed;
    rsp.attr_value.value[2] = 0xbe;
    rsp.attr_value.value[3] = 0xef;
    esp_ble_gatts_send_response(gatts_if, param->read.conn_id, param->read.trans_id, ESP_GATT_OK, &rsp);
    break;
  }
  case ESP_GATTS_WRITE_EVT: // 客户端发起的写事件
  {
    ESP_LOGI(TAG, "GATT_WRITE_EVT, conn_id %d, trans_id %" PRIu32 ", handle %d", param->write.conn_id, param->write.trans_id, param->write.handle);
    if (param->write.handle == gl_profile_tab[PROFILE_A_APP_ID].char_handle)
      ESP_LOGI(TAG, "char_handle");
    else if (param->write.handle == gl_profile_tab[PROFILE_A_APP_ID].descr_handle)
      ESP_LOGI(TAG, "descr_handle");
    else if (param->write.handle == gl_profile_tab[PROFILE_A_APP_ID].service_handle)
      ESP_LOGI(TAG, "service_handle");
    else
      ESP_LOGI(TAG, "unknow_handle");
    if (!param->write.is_prep) // 如果不是预备写操作
    {
      // 打印 写入数据内容
      ESP_LOGI(TAG, "GATT_WRITE_EVT, offset [%d] value len [%d], value: %s", param->write.offset, param->write.len, param->write.value);

      if (gl_profile_tab[PROFILE_A_APP_ID].descr_handle == param->write.handle && param->write.len == 2)
      {
        uint16_t descr_value = param->write.value[1] << 8 | param->write.value[0];
        if (descr_value == 0x0001)
        {
          if (property_a & ESP_GATT_CHAR_PROP_BIT_NOTIFY)
          {
            ESP_LOGI(TAG, "notify enable");
            uint8_t notify_data[15];
            for (int i = 0; i < sizeof(notify_data); ++i)
              notify_data[i] = i % 0xff;

            // the size of notify_data[] need less than MTU size
            esp_ble_gatts_send_indicate(gatts_if, param->write.conn_id, gl_profile_tab[PROFILE_A_APP_ID].char_handle,
                                        sizeof(notify_data), notify_data, false);
          }
        }
        else if (descr_value == 0x0002)
        {
          if (property_a & ESP_GATT_CHAR_PROP_BIT_INDICATE)
          {
            ESP_LOGI(TAG, "indicate enable");
            uint8_t indicate_data[15];
            for (int i = 0; i < sizeof(indicate_data); ++i)
            {
              indicate_data[i] = i % 0xff;
            }
            // the size of indicate_data[] need less than MTU size
            esp_ble_gatts_send_indicate(gatts_if, param->write.conn_id, gl_profile_tab[PROFILE_A_APP_ID].char_handle,
                                        sizeof(indicate_data), indicate_data, true);
          }
        }
        else if (descr_value == 0x0000)
        {
          ESP_LOGI(TAG, "notify/indicate disable ");
        }
        else
        {
          ESP_LOGE(TAG, "unknown descr value");
          esp_log_buffer_hex(TAG, param->write.value, param->write.len);
        }
      }
    }
    example_write_event_env(gatts_if, &a_prepare_write_env, param);
    break;
  }
  case ESP_GATTS_MTU_EVT: // 设置 MTU 事件
  case ESP_GATTS_CREATE_EVT: // 完成创建 服务 事件
  {
    ESP_LOGI(TAG, "ESP_GATTS_CREATE_EVT, status %d,  service_handle %d", param->create.status, param->create.service_handle);
    // 存储服务句柄
    gl_profile_tab[PROFILE_A_APP_ID].service_handle = param->create.service_handle;
    // 新建 characteristic ，定义 UUID
    gl_profile_tab[PROFILE_A_APP_ID].char_uuid.len = ESP_UUID_LEN_16;
    gl_profile_tab[PROFILE_A_APP_ID].char_uuid.uuid.uuid16 = GATTS_CHAR_UUID_A;
    // 启动服务
    ESP_ERROR_CHECK(esp_ble_gatts_start_service(gl_profile_tab[PROFILE_A_APP_ID].service_handle));
    // 设置特征的权限和属性(特性)
    permission_a = ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE;
    property_a = ESP_GATT_CHAR_PROP_BIT_READ | ESP_GATT_CHAR_PROP_BIT_WRITE | ESP_GATT_CHAR_PROP_BIT_NOTIFY;
    // 添加特征
    if (esp_ble_gatts_add_char(gl_profile_tab[PROFILE_A_APP_ID].service_handle,
                               &gl_profile_tab[PROFILE_A_APP_ID].char_uuid,
                               permission_a,
                               property_a,
                               &gatts_char1_val,
                               NULL))
      ESP_LOGE(TAG, "Add characteristic failed");
    break;
  }
  case ESP_GATTS_ADD_CHAR_EVT: // 完成添加特性事件
  {
    uint16_t length = 0;
    const uint8_t *prf_char;
    ESP_LOGI(TAG, "ESP_GATTS_ADD_CHAR_EVT, status %d,  attr_handle %d, service_handle %d", param->add_char.status, param->add_char.attr_handle, param->add_char.service_handle);
    // 存储特性的句柄
    gl_profile_tab[PROFILE_A_APP_ID].char_handle = param->add_char.attr_handle;
    // 新建 description 的 UUID
    gl_profile_tab[PROFILE_A_APP_ID].descr_uuid.len = ESP_UUID_LEN_16;
    gl_profile_tab[PROFILE_A_APP_ID].descr_uuid.uuid.uuid16 = ESP_GATT_UUID_CHAR_DESCRIPTION;
    esp_ble_gatts_get_attr_value(param->add_char.attr_handle, &length, &prf_char);

    // 打印 characteristic 的 value
    ESP_LOGI(TAG, "The GATTS char length = %d", length);
    for (int i = 0; i < length; i++)
      ESP_LOGI(TAG, "prf_char[%d] =%x", i, prf_char[i]);

    // 添加描述符
    if (esp_ble_gatts_add_char_descr(gl_profile_tab[PROFILE_A_APP_ID].service_handle,
                                     &gl_profile_tab[PROFILE_A_APP_ID].descr_uuid,
                                     ESP_GATT_PERM_READ | ESP_GATT_PERM_WRITE,
                                     &gatts_char1_desc_val,
                                     NULL))
      ESP_LOGE(TAG, "Add characteristic`s description failed");
    break;
  }
  case ESP_GATTS_ADD_CHAR_DESCR_EVT: // 完成添加特性描述符事件
  {                                  // 记录描述符句柄
    gl_profile_tab[PROFILE_A_APP_ID].descr_handle = param->add_char_descr.attr_handle;
    ESP_LOGI(TAG, "ESP_GATTS_ADD_CHAR_DESCR_EVT, status %d, attr_handle %d, service_handle %d", param->add_char_descr.status, param->add_char_descr.attr_handle, param->add_char_descr.service_handle);
    break;
  }
  case ESP_GATTS_START_EVT: // 服务启动完成事件
  {
    ESP_LOGI(TAG, "ESP_GATTS_START_EVT, status %d, service_handle %d", param->start.status, param->start.service_handle);
    break;
  }
  case ESP_GATTS_CONNECT_EVT: // 客户端连接事件
  {
    ESP_LOGI(TAG, "ESP_GATTS_CONNECT_EVT, conn_id %d, remote %02x:%02x:%02x:%02x:%02x:%02x:",
             param->connect.conn_id,
             param->connect.remote_bda[0], param->connect.remote_bda[1], param->connect.remote_bda[2],
             param->connect.remote_bda[3], param->connect.remote_bda[4], param->connect.remote_bda[5]);
    // 配置连接参数
    esp_ble_conn_update_params_t conn_params = {0};
    memcpy(conn_params.bda, param->connect.remote_bda, sizeof(esp_bd_addr_t));
    conn_params.latency = 0;
    conn_params.max_int = 0x20; // max_int = 0x20*1.25ms = 40ms
    conn_params.min_int = 0x10; // min_int = 0x10*1.25ms = 20ms
    conn_params.timeout = 400;  // timeout = 400*10ms = 4000ms
    // 记录连接ID
    gl_profile_tab[PROFILE_A_APP_ID].conn_id = param->connect.conn_id;
    // Start sent the update connection parameters to the peer device.
    esp_ble_gap_update_conn_params(&conn_params);
    break;
  }
  case ESP_GATTS_DISCONNECT_EVT: // 客户端断开连接事件
  {
    ESP_LOGI(TAG, "ESP_GATTS_DISCONNECT_EVT, disconnect reason 0x%x", param->disconnect.reason);
    esp_ble_gap_start_advertising(&adv_params);
    break;
  }
  case ESP_GATTS_RESPONSE_EVT:
  {
    ESP_LOGI(TAG, "ESP_GATTS_RESPONSE_EVT: ");
    break;
  }
  default:
  {
    ESP_LOGI(TAG, "ESP_GATTS_XXX_EVT: [%d]", event);
    break;
  }
  }
}

void app_main(void)
{
  esp_err_t ret;

  // Initialize NVS.
  ret = nvs_flash_init();
  if (ret == ESP_ERR_NVS_NO_FREE_PAGES || ret == ESP_ERR_NVS_NEW_VERSION_FOUND)
  {
    ESP_ERROR_CHECK(nvs_flash_erase());
    ret = nvs_flash_init();
  }
  ESP_ERROR_CHECK(ret);

  // Initialize BLE
  ESP_ERROR_CHECK(esp_bt_controller_mem_release(ESP_BT_MODE_CLASSIC_BT));  // 释放 Classic bt 内存
  esp_bt_controller_config_t bt_cfg = BT_CONTROLLER_INIT_CONFIG_DEFAULT(); // 获取默认 controller 配置信息
  ESP_ERROR_CHECK(esp_bt_controller_init(&bt_cfg));                        // 配置 controller
  ESP_ERROR_CHECK(esp_bt_controller_enable(ESP_BT_MODE_BLE));              // 使能 controller 的 ble 功能
  ESP_ERROR_CHECK(esp_bluedroid_init());                                   // 初始化 bluedroid
  ESP_ERROR_CHECK(esp_bluedroid_enable());                                 // 使能 bluedroid
  ESP_ERROR_CHECK(esp_ble_gap_register_callback(gap_event_handler));       // 注册 BLE GAP 事件回调函数
  ESP_ERROR_CHECK(esp_ble_gap_set_device_name(DEVICE_NAME));               // 设置蓝牙设备名称
  ESP_ERROR_CHECK(esp_ble_gatt_set_local_mtu(500));                        // 设置本地 MTU(最大传输单元)
  ESP_ERROR_CHECK(esp_ble_gap_config_adv_data(&adv_data));                 // config adv data
  adv_config_done |= adv_config_flag;
  ESP_ERROR_CHECK(esp_ble_gap_config_adv_data(&scan_rsp_data)); // config scan response data
  adv_config_done |= scan_rsp_config_flag;
  ESP_ERROR_CHECK(esp_ble_gatts_register_callback(gatts_event_handler)); // 注册 BLE GATT 事件回调函数
  ESP_ERROR_CHECK(esp_ble_gatts_app_register(PROFILE_A_APP_ID));         // 注册 BLE-GATTS 应用程序标识符

  return;
}
